// Copyright 2023 Srhino Co., Ltd. All rights reserved.

package log

type loggerOptions struct {
	level string

	// rolling log file options
	fileName   string
	maxSize    int
	maxBackups int
	maxAge     int
	compress   bool

	// std output
	stdOut bool
}

func (opt *loggerOptions) setDefault() {
	if opt.fileName == "" {
		opt.fileName = "log"
	}

	if opt.maxSize <= 0 {
		opt.maxSize = 1024
	}

	if opt.maxBackups <= 0 {
		opt.maxBackups = 1
	}

	if opt.maxAge <= 0 {
		opt.maxAge = 30
	}
}

type LoggerOption interface {
	apply(*loggerOptions)
}

type funcLoggerOption struct {
	f func(*loggerOptions)
}

func (fdo *funcLoggerOption) apply(do *loggerOptions) {
	fdo.f(do)
}

func newFuncLoggerOption(f func(*loggerOptions)) *funcLoggerOption {
	return &funcLoggerOption{
		f: f,
	}
}

// type joinLoggerOption struct {
// 	opts []LoggerOption
// }

// func (mdo *joinLoggerOption) apply(do *loggerOptions) {
// 	for _, opt := range mdo.opts {
// 		opt.apply(do)
// 	}
// }

// func newJoinLoggerOption(opts ...LoggerOption) LoggerOption {
// 	return &joinLoggerOption{opts: opts}
// }

func WithLevel(level string) LoggerOption {
	return newFuncLoggerOption(func(o *loggerOptions) {
		o.level = level
	})
}

func WithFilename(fileName string) LoggerOption {
	return newFuncLoggerOption(func(o *loggerOptions) {
		o.fileName = fileName
	})
}

func WithMaxSize(maxSize int) LoggerOption {
	return newFuncLoggerOption(func(o *loggerOptions) {
		o.maxSize = maxSize
	})
}

func WithMaxBackups(maxBackups int) LoggerOption {
	return newFuncLoggerOption(func(o *loggerOptions) {
		o.maxBackups = maxBackups
	})
}

func WithMaxAge(maxAge int) LoggerOption {
	return newFuncLoggerOption(func(o *loggerOptions) {
		o.maxAge = maxAge
	})
}

func WithCompress(compress bool) LoggerOption {
	return newFuncLoggerOption(func(o *loggerOptions) {
		o.compress = compress
	})
}

func WithStdOut(stdOut bool) LoggerOption {
	return newFuncLoggerOption(func(o *loggerOptions) {
		o.stdOut = stdOut
	})
}

func WithProductionOptions() []LoggerOption {
	return []LoggerOption{
		WithFilename("log"),
		WithLevel("info"),
		WithMaxBackups(30), // 最多支持30个备份文件
		WithMaxAge(30),     // 每份备份文件最多保留30天
		WithMaxSize(100),   // 日志文件最大100Mb
		WithCompress(true),
		WithStdOut(false),
	}
}

func WithDevelopmentOptions() []LoggerOption {
	return []LoggerOption{
		WithFilename("debug.log"),
		WithLevel("debug"),
		WithMaxBackups(30), // 最多支持30个备份文件
		WithMaxAge(30),     // 每份备份文件最多保留30天
		WithMaxSize(100),   // 日志文件最大100Mb
		WithCompress(false),
		WithStdOut(true),
	}
}
